using System.Collections;
using System.Collections.Generic;
using UnityEngine;

/// <summary>
/// 生命汲取Buff - 攻击时恢复生命值
/// </summary>
public class LifeLeechBuff : BuffBase
{
    private float m_LeechPercentage;
    private long m_TotalLeeched;

    public LifeLeechBuff(BuffData buffData, Entity caster, Entity target) : base(buffData, caster, target)
    {
        if (buffData is LifeLeechData leechData)
        {
            m_LeechPercentage = leechData.LeechPercentage;
        }
        else
        {
            m_LeechPercentage = 0.2f; // 默认汲取20%伤害
        }
    }

    protected override void OnStart()
    {
        base.OnStart();
        m_TotalLeeched = 0;
        
        // 播放生命汲取特效
        if (BuffData.Effect != null)
        {
            var effect = GameObject.Instantiate(BuffData.Effect, Target.transform);
            effect.transform.localPosition = Vector3.zero;
        }
        
        Logger.Log("LifeLeechBuff", $"{Target.name} 获得生命汲取效果，汲取{m_LeechPercentage * 100}% 的伤害");
    }

    protected override void OnTick(float dt)
    {
        base.OnTick(dt);
        // 生命汲取期间不需要特殊处理，在攻击时触发
    }

    /// <summary>
    /// 处理生命汲取（在攻击造成伤害时调用）
    /// </summary>
    /// <param name="damageDealt">造成的伤害</param>
    public void ProcessLifeLeech(long damageDealt)
    {
        if (Target == null || Target.HealthComponent.IsDead) return;
        
        // 计算汲取的生命值
        long leechedHealth = (long)(damageDealt * m_LeechPercentage);
        
        // 恢复生命值
        Target.HealthComponent.TakeHeal(leechedHealth);
        m_TotalLeeched += leechedHealth;
        
        Logger.Log("LifeLeechBuff", $"{Target.name} 汲取了{leechedHealth} 点生命值");
        
        // 触发治疗事件
        var args = ReferencePool.Acquire<EntityHealEventArgs>();
        args.Entity = Target;
        args.HealAmount = leechedHealth;
        EventHelper.Fire(this, args);
    }

    protected override void OnFinish()
    {
        base.OnFinish();
        Logger.Log("LifeLeechBuff", $"{Target.name} 生命汲取效果结束，总共汲取了{m_TotalLeeched} 点生命值");
    }

    protected override void OnRemove()
    {
        base.OnRemove();
        
        // 清理特效
        var effects = Target.GetComponentsInChildren<ParticleSystem>();
        foreach (var effect in effects)
        {
            if (effect.name.Contains("LifeLeech"))
            {
                GameObject.Destroy(effect.gameObject);
            }
        }
    }

    public override bool IsCanMerge()
    {
        return true; // 生命汲取效果可以叠加，刷新持续时间
    }

    /// <summary>
    /// 获取总汲取量
    /// </summary>
    public long GetTotalLeeched()
    {
        return m_TotalLeeched;
    }
}